<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">楼宇名称：</div>
      <el-input
        v-model="params.name"
        placeholder="请输入内容"
        class="search-main"
        clearable
        @clear="doSearch"
      />
      <el-button type="primary" @click="doSearch()">查询</el-button>
    </div>
    <div class="create-container">
      <el-button type="primary" @click="addBuilding">添加楼宇</el-button>
      <el-button @click="exportToExcel">导出Excel</el-button>

    </div>
    <!-- 添加楼宇弹框 -->
    <el-dialog
      :title="title"
      :visible="dialogVisible"
      width="580px"
      @close="closeDialog"
    >
      <div class="form-container">
        <el-form ref="addForm" :model="addForm" :rules="addFormRules">
          <el-form-item label="楼宇名称" prop="name">
            <el-input v-model="addForm.name" placeholder="请输入楼宇名称" />
          </el-form-item>
          <el-form-item label="楼宇层数" prop="floors">
            <el-input v-model="addForm.floors" placeholder="请输入楼宇层数" />
          </el-form-item>
          <el-form-item label="在管面积" prop="area">
            <el-input v-model="addForm.area" placeholder="请输入在管面积">
              <template slot="append">㎡</template>
            </el-input>
          </el-form-item>
          <el-form-item label="物业费" prop="propertyFeePrice">
            <el-input
              v-model="addForm.propertyFeePrice"
              placeholder="请输入物业费"
            >
              <template slot="append">元/㎡</template>

            </el-input>
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <el-button size="mini" @click="dialogVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="confirmAdd">确 定</el-button>
      </template>
    </el-dialog>

    <!-- 表格区域 -->
    <div class="table">
      <el-table
        style="width: 100%"
        :data="bulidList"
      >
        <el-table-column
          type="index"
          label="序号"
          width="200"
        />
        <el-table-column
          label="楼宇名称"
          width="200"
          prop="name"
        />
        <el-table-column
          label="层数"
          prop="floors"
        />
        <el-table-column
          label="在管面积(m²)"
          width="200"
          prop="area"
        />
        <el-table-column
          label="物业费(元/m²)"
          width="200"
          prop="propertyFeePrice"
        />
        <el-table-column
          label="状态"
          prop="status"
        >
          <template #default="scope">
            {{ getStatus(scope.row.status) }}
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="200"
        >
          <template #default="scope">
            <el-button
              size="mini"
              type="text"
              @click="getBuilding(scope.row)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="text"
              :disabled="scope.row.status === 0"
              @click="confirmDel(scope.row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination
        background
        layout="total, prev, pager, next,sizes,jumper"
        :total="total"
        :page-size="params.pageSize"
        :page-sizes="[5, 10, 15, 30]"
        :current-page="params.page"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </div>

  </div>
</template>

<script>
import { getBuildingListAPI, createBuildingListAPI, delBuildingListAPI, editBuildingAPI
} from '@/api/building'
import { utils, writeFileXLSX } from 'xlsx'

export default {
  name: 'Building',
  data() {
    return {
      title: '添加楼宇',
      total: 0,
      params: { name: '', page: 1, pageSize: 10 },
      bulidList: [],
      dialogVisible: false,
      addForm: {
        name: '',
        floors: '',
        area: '',
        propertyFeePrice: ''
      },
      addFormRules: {
        name: [{ required: true, message: '请输入楼宇名称', trigger: 'blur' }],
        floors: [{ required: true, message: '请输入楼宇层数', trigger: 'blur' }],
        area: [{ required: true, message: '请输入楼宇面积', trigger: 'blur' }],
        propertyFeePrice: [{ required: true, message: '请输入楼宇物业费', trigger:
'blur' }] }

    }
  },
  mounted() {
    this.getBuildingList()
  },
  methods: {
    async  getBuildingList() {
      const res = await getBuildingListAPI(this.params)
      // console.log(this.params)
      this.bulidList = res.data.rows
      this.total = res.data.total
      // console.log(this.bulidList)
    },
    getStatus(status) {
      const statusMap = {
        0: '租赁中',
        1: '闲置中'
      }
      return statusMap[status]
    },
    // 页码触发函数
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      // 更改参数
      this.params.pageSize = val
      this.getBuildingList()
    },
    handleCurrentChange(val) {
      this.params.page = val
      this.getBuildingList()
    },
    doSearch() {
      // 1.重置表单
      this.params.page = 1
      // 2.调用获取列表接口
      this.getBuildingList()
    },
    // 打开窗口
    addBuilding() {
      this.title = '添加楼宇'
      console.log(this.addForm)
      this.dialogVisible = true
    },
    // 关闭窗口
    closeDialog() {
      this.dialogVisible = false
      this.addForm = { name: '', floors: '', area: '', propertyFeePrice: '' }
      this.$refs.addForm.resetFields()
    },
    // 提交
    confirmAdd() {
      this.$refs.addForm.validate(async(valid) => {
        if (valid) {
          console.log(this.addForm)
          if (this.addForm.id) {
            console.log(1)
            console.log(this.addForm)
            await editBuildingAPI(this.addForm)
          } else {
            // console.log(this.addForm)
            await createBuildingListAPI(this.addForm)
          }
          // 1.提交
          // 2.获取列表
          this.getBuildingList()
          // 3.关闭弹窗
          this.dialogVisible = false
        }
      })
    },
    // 删除
    confirmDel(id) {
      console.log(id)
      this.$confirm('确定删除当前楼宇吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delBuildingListAPI(id)
        this.getBuildingList()
      }).catch(() => {
      })
    },
    getBuilding(row) {
      this.title = '编辑楼宇'
      // console.log(row)
      // 1. 打开弹框
      this.dialogVisible = true
      // 2. 解构必要字段
      const { id, area, floors, name, propertyFeePrice } = row
      this.addForm = { id, area, floors, name,
        propertyFeePrice }
    },
    async exportToExcel() {
      const res = await getBuildingListAPI(this.params)
      const tableHeader = ['name', 'floors', 'area', 'propertyFeePrice', 'status']
      // 处理数据保证
      const sheetData = res.data.rows.map((item) => {
        const obj = {}
        tableHeader.forEach(key => {
          obj[key] = item[key]
        })
        return obj
      })
      // 创建一个工作表
      const worksheet = utils.json_to_sheet(sheetData)
      // 创建一个新的工作簿
      const workbook = utils.book_new()
      // 把工作表添加到工作簿
      utils.book_append_sheet(workbook, worksheet, 'Data')
      // 改写表头
      utils.sheet_add_aoa(worksheet, [['楼宇名称', '层数', '在管面积(㎡)',
        '物业费(㎡)', '状态']], { origin: 'A1' })
      writeFileXLSX(workbook, 'SheetJSVueAoO.xlsx')
    }

  }

}
</script>

<style lang="scss" scoped>
.department-container {
  padding: 10px;
}
.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, 0.9);
  padding-bottom: 20px;
  .search-label {
    width: 100px;
  }
  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}
.page-container { padding: 4px 0px; text-align: right; }
.create-container { margin: 10px 0px; }

</style>
